AddCSLuaFile( "cl_init.lua" )
AddCSLuaFile( "shared.lua" )
include('shared.lua')

function ENT:SpawnFunction( ply, tr)
	local SpawnPos = tr.HitPos + tr.HitNormal * 100
	local ent = ents.Create( "vehicle" )
	ent:SetPos( SpawnPos )
	ent:Spawn()
	ent:Activate()
	return ent
end

function ENT:Initialize()
	self.Entity:SetUseType( SIMPLE_USE )
	self.Firee=nil
	self.Inflight=false
	self.Pilot=nil
	self.Entity:SetModel("models/props_combine/headcrabcannister01a.mdl")	
	self.Entity:PhysicsInit( SOLID_VPHYSICS )
	self.Entity:SetMoveType( MOVETYPE_VPHYSICS )
	self.Entity:SetSolid( SOLID_VPHYSICS )
		local phys = self.Entity:GetPhysicsObject()
		if (phys:IsValid()) then
			phys:Wake()
			phys:SetMass(500)
		end
	self.Accel=0
	self.exitseconds = 0
end

function ENT:OnRemove()
	if self.Pilot then
		local plyuni = self.Pilot:UniqueID()
		self.Pilot:UnSpectate()
		if 	servertable["ply"][plyuni] then
			servertable["ply"][plyuni]["Inpod"] = false
			local rp = RecipientFilter()
			rp:AddPlayer(self.Pilot)
			umsg.Start("InVehicle", rp)
			umsg.Bool(false)
			umsg.End()
			self.Pilot:Kill()
		end
	end
end

function ENT:Think()
	if self.Inflight and self.Pilot and self.Pilot:IsValid() then
		self.Pilot:SetPos(self.Entity:GetPos())
		if self.Pilot:KeyDown(IN_USE) then
			self.exitseconds = self.exitseconds +1
			self.Pilot:PrintMessage(HUD_PRINTCENTER, "Hold Use to exit , exit in " .. 6 - self.exitseconds )
			if ( self.exitseconds > 5) then
				local plyuni = self.Pilot:UniqueID()
				self.Pilot:UnSpectate()
				self.Pilot:DrawViewModel(true)
				self.Pilot:DrawWorldModel(true)
				self.Pilot:Spawn()
				self.Pilot:SetPos(self.Entity:GetPos()+Vector(50,0,50))
				self.exitseconds = 0
				local rp = RecipientFilter()
				rp:AddPlayer(self.Pilot)
				umsg.Start("InVehicle", rp)
				umsg.Bool(false)
				umsg.End()
				servertable["ply"][plyuni]["Inpod"] = false
				self.Inflight=false
				if self.Firee then
					self.Firee:Remove()
				end
				self.Entity:SetLocalVelocity(Vector(0,0,0))
				self.Pilot=nil
			end
		else
			self.exitseconds = 0
		end
	end
	self.Entity:NextThink(CurTime()+0.2)
	return true
end

function ENT:Use(ply,caller)
	if self.Inflight then 
	else
		local plyuni = ply:UniqueID()
		RegisterShip(self.Entity,plyuni)
		self.Entity:GetPhysicsObject():Wake()
		self.Entity:GetPhysicsObject():EnableMotion(true)
		self.Inflight=true
		self.Pilot=ply
		ply:Spectate( 4 )
		ply:SpectateEntity(self.Entity)
		ply:DrawViewModel(false)
		ply:DrawWorldModel(false)
		ply:StripWeapons()
		servertable["ply"][plyuni]["Inpod"] = true
		ply.Vehicle = self.Entity
		local rp = RecipientFilter()
		rp:AddPlayer(ply)
		umsg.Start("InVehicle", rp)
		umsg.Bool(true)
		umsg.Entity(self.Entity)
		umsg.End()
	end
end

function ENT:OnTakeDamage(info)
	Shieldhit(info,self.Entity)
end